package com.shop.loan.proxy;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.view.StatisticsByLoanDay;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsByLoanDayProxy implements DataProxy<StatisticsByLoanDay> {

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    Util util;

    @Override
    public String beforeFetch(List<Condition> conditions) {
        conditions.removeIf(condition -> "channel".trim().equals(condition.getKey()));
        return null;
    }

    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        String channelIdStr = util.getSearchParam("channel", 1);
        Long channelId = StringUtils.hasLength(channelIdStr) ? Long.valueOf(channelIdStr) : null;
        for (Map<String, Object> stringObjectMap : list) {
            String dayStr = stringObjectMap.get("day").toString();
            DateTime dayTime = DateUtil.parse(dayStr);
            String timeStartStr = DateUtil.beginOfDay(dayTime).toString();
            String timeEndStr = DateUtil.endOfDay(dayTime).toString();

            LoanOrderByMybatis loanOrderByMybatis = new LoanOrderByMybatis();
            loanOrderByMybatis.setStartTimeByLoan(timeStartStr);
            loanOrderByMybatis.setEndTimeByLoan(timeEndStr);
            loanOrderByMybatis.setChannelId(channelId);
            loanOrderByMybatis.setUserType(Integer.parseInt(stringObjectMap.get("type").toString()));
            //订单总数
//            Integer totalOrderNum = loanOrderByMybatisMapper.selectNum(loanOrderByMybatis);

            loanOrderByMybatis.setAuthStatus(1);
            //审核通过数量
            Integer successOrderNum = loanOrderByMybatisMapper.selectNum(loanOrderByMybatis);

            BigDecimal money = BigDecimal.ZERO, loanMoney = BigDecimal.ZERO;
            LoanOrderByMybatis sumOrder = loanOrderByMybatisMapper.selectSum(loanOrderByMybatis);
            if (sumOrder != null) {
                money = sumOrder.getMoney().add(sumOrder.getRateMoney()).add(sumOrder.getShopMoney());
                loanMoney = sumOrder.getMoney();
            }
//            stringObjectMap.put("totalOrderNum",totalOrderNum);
            stringObjectMap.put("successOrderNum", successOrderNum);
            stringObjectMap.put("money", money);
            stringObjectMap.put("loanMoney", loanMoney);
        }
    }
}
